var config = require('../config.js')
const util = require('./util.js')

/**
 * 发送请求
 * @body {String} method get|post
 * @body {String} url 接口地址
 * @body {JSON} header.ContentType 请求头
 * @body {*} data 请求数据
 * @body {JSON} auth.noAuth 无需登陆权限 & auth.noVerify 无需检验返回状态code
 */
export default function request(method, params) {
  // 1、拼接url
  const url = params.uploadUrl ? params.uploadUrl : (params.domain ? params.domain : config.DOMAIN) + params.url
  // 2、拼接head
  const head = {
    'Authorization': uni.getStorageSync('token'),
    'locale': uni.getStorageSync('lang') || 'zh_CN'
  }
  head['Content-Type'] = 'application/x-www-form-urlencoded'
  if (params.header && params.header.ContentType) {
    head['Content-Type'] = params.header.ContentType
  }
  // 3、发起请求
  return new Promise((reslove, reject) => {
    uni.request({
      url: url,
      data: params.data,
      header: head,
      method: method || 'GET',
      success: function(res) {
        if (res.statusCode !== 200) {
          util.Tips({ title: '服务器出了点小差~' })
          reject('服务器出了点小差~')
        } else if (res.data.code === 1) {
          util.Tips({ title: res.data.msg })
          reject(res.data, res)
        } else if (res.data.code === 0) {
          reslove(res.data, res)
        } else if (res.data.code === 9) {
          console.log('请求401')
          // util.logout()
          uni.hideLoading()
          // to re-login
          uni.showModal({
            title: '提示',
            content: '登录已过期，请重新登录',
            success: modalRes => {
              if (modalRes.confirm) {
                // 跳转登录页面
                let url = url = '/pages/users/login/index'
                uni.navigateTo({
                  url: url
                })
              } else if (modalRes.cancel) {
                uni.switchTab({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      },
      fail: function(err) {
        uni.hideLoading()
        setTimeout(() => {
          uni.showToast({
            title: '服务器打了个盹~',
            icon: 'none'
          })
        }, 1)
        reject(url + ' ' + err.errMsg)
      }
    })
  })
}

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
  request[method] = (params) => request(method, params)
})
